package org.xiaojl.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Properties 文件读取工具类
 */
public class PropertiesUtil {
	private static final Logger log = LoggerFactory.getLogger(PropertiesUtil.class);
	private static final String CONFIG_FILE_NAME = "application.properties";
	private static Properties pro = null;
	
	/**
     * 读取配置文件,初始化Properties
     */
	public static void init() {
		log.info("读取配置文件,初始化Properties对象");
		if(pro == null){
			pro = new Properties();
		}
		InputStream in = null;
        try {
            in = PropertiesUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME);
            if (in != null) {
            	pro.load(in);
            }
        } catch (IOException e) {
        	log.error("初始化配置文件 " + CONFIG_FILE_NAME + " 发生错误,请检查相关配置文件!" ,e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                	log.error("关闭 " + CONFIG_FILE_NAME + " 出现异常!");
                }
            }
        }
	}
	
	/**
     * 封装了Properties类的getProperty函数 
     */
    public static String getProperty(String key, String defaultValue) {
    	if(pro == null){
    		init();
    	}
        if (pro.getProperty(key) == null) {
            return defaultValue;
        }else{
            return pro.getProperty(key);
        }

    }

    /**
     * 封装了Properties类的getProperty函数,
     */
    public static String getProperty(String key) {
        return getProperty(key, null);
    }
    
    public static void main(String[] args) {
		System.out.println(getProperty("db.master.url"));
	}

}
